package com.hencoder.hencoderpracticedraw1.practice;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

public class Practice10HistogramView extends View {

    private String[] strings = {"Froyo", "GB", "ICS", "JB", "KitKat", "L", "M"};
    private float[] heights = {2, 15, 15, 180, 250, 300, 170};
    private Paint paint;
    private int startX = 150;
    private int startY = 50;
    private int endY = 500;
    private int width = 80;
    private int x;


    public Practice10HistogramView(Context context) {
        super(context);
    }

    public Practice10HistogramView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public Practice10HistogramView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.WHITE);
        //绘制竖线
        canvas.drawLine(startX, startY, startX, endY, paint);
        //绘制横线
        canvas.drawLine(startX, endY, 900, endY, paint);
        x = 200;
        paint.setColor(Color.WHITE);
        paint.setTextSize(24);
        paint.setStyle(Paint.Style.FILL);
        //该方法即为设置基线上那个点到底是left,center,还是right  这里我设置为center
        paint.setTextAlign(Paint.Align.CENTER);

        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        float top = fontMetrics.top;//为基线到字体上边框的距离,即上图中的top
        float bottom = fontMetrics.bottom;//为基线到字体下边框的距离,即上图中的bottom

        for (String text : strings) {
            Rect rect = new Rect(x, endY, x + width, endY + 40);
            Paint rectPaint = new Paint();
            rectPaint.setColor(Color.TRANSPARENT);
            rectPaint.setStyle(Paint.Style.FILL);
            canvas.drawRect(rect, rectPaint);

            int baseLineY = (int) (rect.centerY() - top / 2 - bottom / 2);//基线中间点的y轴计算公式

            canvas.drawText(text, rect.centerX(), baseLineY, paint);
            x = x + width + 20;
        }

        paint.setTextSize(36);
        canvas.drawText("直方图",500, 600, paint);

        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.parseColor("#72B916"));
        x = 200;
        //绘制
        for (float heigth : heights) {
            canvas.drawRect(x, endY - heigth, x + width, endY, paint);
            x = x + width + 20;
        }

    }

//        综合练习
//        练习内容：使用各种 Canvas.drawXXX() 方法画直方图

}
